<template>
  <div class="container" :style="{ fontWeight: formState.disabled ? 'bold' : 'normal' }">
    <Breadcrumb :items="['赛事管理', '赛事列表']" />
    <div class="">
      <div class="header">
        <a-button type="primary" @click="handleClick">发布赛事</a-button>
        <a-modal 
          v-model:visible="visible" 
          @ok="handleOk" 
          @cancel="handleCancel">
        <template #title> 发布赛事 </template>
          <div>
            <a-form :model="releaseMatch" @finish-submit="handleOk">
              <a-form-item field="matchTitle" label="赛事名称">
                <a-input v-model="publishMatchTitle" placeholder="请输入赛事名称" />
              </a-form-item>
              <a-form-item field="matchType" label="赛事类型">
                <a-select v-model="publishMatchType" placeholder="请选择" allow-clear>
                  <a-option value="1">积分赛</a-option>
                  <a-option value="2">常规赛</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="raceMethod" label="比赛方式">
                <a-select v-model="publishRaceMethod" placeholder="请选择" allow-clear>
                  <a-option value="1">五次取平均</a-option>
                  <a-option value="2">全部取平均</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="groupItemId" label="组别">
                <a-select v-model="publishGroupItemId" placeholder="请选择" allow-clear>
                  <a-option value="1">女子组</a-option>
                  <a-option value="2">新人组</a-option>
                </a-select>
              </a-form-item>
              <a-form-item field="itemList" label="赛项">
                <a-checkbox-group :style="{width:'320px'}" @change="selectedItemListChange" v-model="selectedItemList">
                  <a-checkbox value="1">二阶</a-checkbox>
                  <a-checkbox value="2">三阶</a-checkbox>
                  <a-checkbox value="3">四阶</a-checkbox>
                  <a-checkbox value="4">五阶</a-checkbox>
                  <a-checkbox value="5">三盲</a-checkbox>
                  <a-checkbox value="6">单手</a-checkbox>
                  <a-checkbox value="7">金字塔</a-checkbox>
                  <a-checkbox value="8">斜转</a-checkbox>
                </a-checkbox-group>
              </a-form-item>
              <a-form-item v-for="(item, index) in selectedItemList" :key="index" field="scheduleList" :label="itemListLabels.find(label => label.value === parseInt(item))?.label">
                <a-select
                  v-model="selectedScheduleList[index].schedule"
                  multiple
                  placeholder="请选择赛程">
                  <a-option value="1">初赛</a-option>
                  <a-option value="2">复赛</a-option>
                  <a-option value="3">半决赛</a-option>
                  <a-option value="4">决赛</a-option>
                </a-select>
              </a-form-item>
              <!-- <a-form-item field="integralDis" label="积分分配">
                <a-input
                  :style="{width:'120px', margin:'0 5px 0 0'}"
                  placeholder="请输入名次前多少名">
                </a-input>
                <a-input 
                  multiple
                  placeholder="请输入分配积分">
                </a-input>
              </a-form-item> -->
              <a-form-item label="比赛时间">
                <a-range-picker
                  style="width: 360px; margin: 0 24px 24px 0;"
                  show-time
                  :time-picker-props="{ defaultValue: ['00:00:00', '09:09:06'] }"
                  format="YYYY-MM-DD HH:mm"
                  v-model="publishDatePicker"
                />
              </a-form-item>
            </a-form>
          </div>
        </a-modal>
        <a-space direction="vertical" size="large">
          <a-input-search 
            :style="{width:'360px', marginLeft: '20px'}" 
            placeholder="Please enter something" 
            search-button 
            allow-clear
            v-model="searchValue"
            @search="handleSearch"
            @clear="searchClear"
          />
        </a-space>
      </div>
      <a-table :data="data" :pagination="false">
        <template #columns>
          <a-table-column title="ID" data-index="matchScheduleId"></a-table-column>
          <a-table-column title="赛事名称" data-index="matchTitle"></a-table-column>
          <a-table-column title="赛事类型" data-index="matchType"></a-table-column>
          <a-table-column title="比赛方式" data-index="raceMethod"></a-table-column>
          <a-table-column title="开始时间" data-index="startTime"></a-table-column>
          <a-table-column title="结束时间" data-index="endTime"></a-table-column>
          <a-table-column title="是否审核" data-index="approveStatus"></a-table-column>
          <a-table-column title="发布人" data-index="nickName"></a-table-column>
          <a-table-column title="发布时间" data-index="createTime"></a-table-column>
          <a-table-column title="操作" data-index="operation">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" @click="handleSetRecordFunc(record)">查看赛程</a-button>
                <a-modal 
                  v-model:visible="showForm" 
                  title="查看赛程" 
                  @ok="handleSubmit" 
                  @cancel="handleModalCancel" 
                  :maskStyle="{'opacity':'0.15','background':'#FFFFF','animation':'none'}">
                  <a-list
                    :scrollbar="scrollbar" 
                    :max-height="400" 
                    :bordered="false">
                    <a-list-item :key="index" v-for="(item, index) in formState">
                      <a-list-item-meta :description="item"></a-list-item-meta>
                    </a-list-item>
                  </a-list>
                </a-modal>
                <a-button type="primary" @click="handleUpdatedRecordFunc(record)">更新</a-button>
                <a-modal 
                  v-model:visible="updatedVisible" 
                  @ok="handleUpdatedOK" 
                  @cancel="updatedVisible = false"
                  :maskStyle="{'opacity':'0.15','background':'#FFFFF','animation':'none'}">
                  <template #title>更新赛事</template>
                  <div>
                    <a-form :model="updatedMatch" @finish-submit="handleUpdatedOK(record)">
                      <a-form-item field="matchTitle" label="赛事名称">
                        <a-input v-model="updatedMatchTitle" placeholder="请输入赛事名称" />
                      </a-form-item>
                      <a-form-item field="matchType" label="赛事类型">
                        <a-select v-model="updatedMatchType" placeholder="请选择" allow-clear>
                          <a-option value="1">积分赛</a-option>
                          <a-option value="2">常规赛</a-option>
                        </a-select>
                      </a-form-item>
                      <a-form-item field="raceMethod" label="比赛方式">
                        <a-select v-model="updatedRaceMethod" placeholder="请选择" allow-clear>
                          <a-option value="1">五次取平均</a-option>
                          <a-option value="2">全部取平均</a-option>
                        </a-select>
                      </a-form-item>
                      <a-form-item field="groupItemId" label="组别">
                        <a-select v-model="updatedGroupItemId" placeholder="请选择" allow-clear>
                          <a-option value="1">女子组</a-option>
                          <a-option value="2">新人组</a-option>
                        </a-select>
                      </a-form-item>
                      <a-form-item field="itemList" label="赛项">
                        <a-checkbox-group :style="{width:'320px'}" @change="updatedItemListChange" v-model="updatedItemList">
                          <a-checkbox value="1">二阶</a-checkbox>
                          <a-checkbox value="2">三阶</a-checkbox>
                          <a-checkbox value="3">四阶</a-checkbox>
                          <a-checkbox value="4">五阶</a-checkbox>
                          <a-checkbox value="5">三盲</a-checkbox>
                          <a-checkbox value="6">单手</a-checkbox>
                          <a-checkbox value="7">金字塔</a-checkbox>
                          <a-checkbox value="8">斜转</a-checkbox>
                        </a-checkbox-group>
                      </a-form-item>
                      <a-form-item 
                        v-for="(item, index) in updatedItemList" 
                        :key="index" 
                        field="scheduleList" 
                        :label="itemListLabels.find(label => label.value === parseInt(item))?.label">
                        <a-select
                          v-model="updatedScheduleList[index].schedule"
                          multiple
                          placeholder="请选择赛程">
                          <a-option value="1">初赛</a-option>
                          <a-option value="2">复赛</a-option>
                          <a-option value="3">半决赛</a-option>
                          <a-option value="4">决赛</a-option>
                        </a-select>
                      </a-form-item>
                      <a-form-item label="比赛时间">
                        <a-range-picker
                          style="width: 360px; margin: 0 24px 24px 0;"
                          show-time
                          :time-picker-props="{ defaultValue: ['00:00:00', '09:09:06'] }"
                          format="YYYY-MM-DD HH:mm"
                          v-model="updatedDatePicker"
                        />
                      </a-form-item>
                    </a-form>
                  </div>
                </a-modal>
                <a-button type="primary" @click="deleteVisible = true">删除</a-button>
                <a-modal 
                  v-model:visible="deleteVisible" 
                  @ok="handleDeleteOk(record)" 
                  @cancel="deleteVisible = false" 
                  :maskStyle="{'opacity':'0.15','background':'#FFFFF','animation':'none'}">
                  <div>是否删除这条信息?</div>
                </a-modal>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div style="width: 100%;margin: 10px auto;">
        <a-pagination @change="pageChange" :total="total" :current="curPage" :page-size="pageSize" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { onMounted, ref } from 'vue';
  import axios from 'axios';

  interface ItemLabel {
    value: number;
    label: string;
  }

  export default {
    setup() {
      const data = ref([]);
      const curPage = ref(1)
      const pageSize = ref(8)
      const total = ref(1)
      const searchData = ref({
        searchField:'race_method',
      })
      const searchValue = ref()

      const itemListLabels: ItemLabel[] = [
        { value: 1, label: '二阶' },
        { value: 2, label: '三阶' },
        { value: 3, label: '四阶' },
        { value: 4, label: '五阶' },
        { value: 5, label: '三盲' },
        { value: 6, label: '单手' },
        { value: 7, label: '金字塔' },
        { value: 8, label: '斜转' }
      ];
      const scheduleListLabels: ItemLabel[] = [
        { value: 1, label: '初赛' },
        { value: 2, label: '复赛' },
        { value: 3, label: '半决赛'},
        { value: 4, label: '决赛' }
      ];

      const selectedItemList = ref([])
      const selectedScheduleList = ref([])
      const publishMatchTitle = ref('')
      const publishMatchType = ref('')
      const publishRaceMethod = ref('')
      const publishGroupItemId = ref('')
      const publishDatePicker = ref([])

      const reqTableListData = () => {
        data.value  = []
        axios.get(`/match/list`, {
          params: {
            curPage: curPage.value,
            pageSize: pageSize.value,
            searchField: searchData.value.searchField,
            search: searchValue.value,
          }
        }).then((res1:any) => {
          console.log(res1);
          curPage.value = res1.current
          pageSize.value = res1.size
          total.value = res1.total
          res1.records.forEach((item:{ matchType:any; raceMethod:any; approveStatus:any; scheduleList:any; itemList:any}) => {
            item.matchType = item.matchType === 1 ? '积分赛' : '常规赛'
            item.raceMethod = item.raceMethod === 1 ? '五次取平均' : '全部取平均'
            item.approveStatus = item.approveStatus === 0 ? '待审核' : '审核通过'
            console.log(item.scheduleList);
            data.value.push(item);
          })
        })
      }

      onMounted(async()=>{
        await reqTableListData()
      });

      const formState = ref({});
      const showForm = ref<boolean>(false);
      const handleSetRecordFunc = (record:any) => {
        showForm.value = true;
        formState.value = [];
        console.log(record)
        record.scheduleList.forEach(item => {
          const itemLabel = itemListLabels.find(label => label.value === item.itemId)?.label;
          if (itemLabel) {
            const scheduleLabels = item.schedule.map(scheduleId => {
              return scheduleListLabels.find(label => label.value === scheduleId)?.label || '';
            });
            // 将 itemId 和 schedule 的标签合并成一个字符串
            const combinedLabels = `${itemLabel}: ${scheduleLabels.join('-')}`;
            formState.value.push(combinedLabels)
          }
        });
      };
      const handleSubmit = () => {
        reqTableListData()
        showForm.value = false
      };
      const handleModalCancel = () => {
        showForm.value = false; // 隐藏模态框
      } 

      const visible = ref(false);
      const releaseMatch = ref({
        matchTitle: '',
        matchType: '',
        raceMethod:'',
        itemList:'',
        scheduleList:'',
        integralDis:'',
      })
      const handleClick = () => {
        visible.value = true;
      };
      const handleOk = () => {
        visible.value = false;
        console.log(selectedScheduleList.value);
        console.log(publishMatchTitle.value);
        console.log(publishMatchType.value);
        console.log(publishRaceMethod.value);
        console.log(publishGroupItemId.value);
        console.log(publishDatePicker.value);
        axios.post(`/match/create/pointRace`, {
          "endTime": publishDatePicker.value[1],
          "groupItemId": publishGroupItemId.value,
          "integralDis": [
            {
              "integral": 0,
              "ranking": 0
            }
          ],
          "itemList": selectedItemList.value,
          "matchTitle": publishMatchTitle.value,
          "matchType": publishMatchType.value,
          "quarterFinalNum": 0,
          "raceMethod": publishRaceMethod.value,
          "scheduleList": selectedScheduleList.value,
          "semiFinalNum": 0,
          "startTime": publishDatePicker.value[0]
        }).then(res => {
          console.log(res.data)
          visible.value = false
          reqTableListData()
        })
      };
      const handleCancel = () => {
        visible.value = false;
      };

      const pageChange = (current) => {
          curPage.value = current
          reqTableListData()
      }

      const handleSearch = () => {
          reqTableListData();
      }
      const searchClear = () => {
        reqTableListData()
      }

      const selectedItemListChange = (value) => {
        console.log(value);
        console.log(selectedItemList);
        selectedScheduleList.value = []
        selectedItemList.value.forEach(v => {
            selectedScheduleList.value.push({
              itemId: v,
              schedule: []
            })
        })
        console.log(selectedScheduleList.value);
        
      }

      const updatedItemList = ref([])
      const updatedScheduleList = ref([])
      const updatedMatchTitle = ref('')
      const updatedMatchType = ref('')
      const updatedRaceMethod = ref('')
      const updatedGroupItemId = ref('')
      const updatedDatePicker = ref([] as any)
      const updatedVisible = ref(false)
      const updatedMatch = ref({
        matchScheduleId:'',
        matchTitle:'',
        matchType: '',
        raceMethod:'',
        itemList:'',
        scheduleList:'',
        integralDis:'',
      })
      const handleUpdatedRecordFunc = (record:any) => {
        updatedVisible.value = true
        console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
        console.log(record)
        console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
        updatedMatch.value.matchScheduleId = record.matchScheduleId
        updatedGroupItemId.value = record.groupItemId === "女子组" ? '1' : '2'
        // updatedItemList.value = record.itemList
        updatedItemList.value = []
        record.itemList.forEach(v => {
          updatedItemList.value.push(`${v}`)
        })
        updatedMatchTitle.value = record.matchTitle
        updatedMatchType.value = record.matchType === "积分赛" ? '1' : '2'
        updatedRaceMethod.value = record.raceMethod === "五次取平均" ? '1' : '2'
        // selectedScheduleList.value = record.selectedScheduleList
        // updatedScheduleList.value = record.scheduleList
        
        updatedScheduleList.value = []
        updatedDatePicker.value[0] = record.startTime
        updatedDatePicker.value[1] = record.endTime
        record.scheduleList.forEach(v => {
          const tmp = []
          v.schedule.forEach(vv => {
            tmp.push(`${vv}`)
          })
          updatedScheduleList.value.push({
            itemId: `${v.itemId}`,
            schedule: tmp
          })
        })
      }
      const handleUpdatedOK = () => {
        updatedVisible.value = false
        axios.put(`/match/update/pointRace`, {
          "endTime": updatedDatePicker.value[1],
          "groupItemId": updatedGroupItemId.value,
          "integralDis": [
            {
              "integral": 0,
              "ranking": 0
            }
          ],
          "itemList": updatedItemList.value,
          "matchScheduleId": updatedMatch.value.matchScheduleId,
          "matchTitle": updatedMatchTitle.value,
          "matchType": updatedMatchType.value,
          "quarterFinalNum": 0,
          "raceMethod": updatedRaceMethod.value,
          "scheduleList": updatedScheduleList.value,
          "semiFinalNum": 0,
          "startTime": updatedDatePicker.value[0]
        }).then(res => {
          console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
          console.log(res.data)
          console.log(updatedDatePicker.value)
          console.log(updatedGroupItemId.value)
          console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
          updatedVisible.value = false
          reqTableListData()
        })
      }

      const deleteVisible = ref(false)
      const handleDeleteOk = (record:any) => {
        axios.delete(`/match/delete/${record.matchScheduleId}`).then(res => {
          deleteVisible.value = false
          reqTableListData()
        })
      }

      const updatedItemListChange = (value) => {
        updatedScheduleList.value = []
        updatedItemList.value.forEach(v => {
            updatedScheduleList.value.push({
              itemId: v,
              schedule: []
            })
        })
        console.log(value);
        
      }

      return {
        data,
        curPage,pageSize,total,pageChange,
        reqTableListData,
        searchData,searchValue,handleSearch,searchClear,
        visible,handleClick,handleOk,handleCancel,
        showForm,formState,handleSubmit,handleSetRecordFunc,
        scheduleListLabels,itemListLabels,handleModalCancel,releaseMatch,
        selectedItemList, selectedItemListChange,selectedScheduleList,
        publishMatchTitle,publishMatchType,publishRaceMethod,publishGroupItemId,publishDatePicker,
        updatedVisible,updatedMatch,handleUpdatedOK,handleUpdatedRecordFunc,
        updatedItemList,updatedMatchTitle,updatedMatchType,updatedRaceMethod,updatedGroupItemId,updatedDatePicker,
        deleteVisible,handleDeleteOk,
        updatedScheduleList, updatedItemListChange
      };
    },
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .header {
    display: flex;
    padding: 20px;
    align-items: center;
    margin-bottom: 10px;
    background-color: #fff;
  }
</style>

<style lang="less" scoped>
  .mobile {
    .content {
      display: block;
      &-left {
        margin-right: 0;
        margin-bottom: 16px;
      }
      &-right {
        width: 100%;
      }
    }
  }
</style>
